import Vue from 'vue'
import Vuex from 'vuex'

import { loginAPI } from '../api/login'

import Storage from '@/utils/storage'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 严格模式 一切数据的修改 只能通过 mutations修改
  strict: true,
  state: {
    token: window.localStorage.getItem('token') || '',
    refreshToken: window.localStorage.getItem('refresh_token') || '',
    // 用户信息
    userInfo: {
      name: '',
      // 头像本地获取
      // photo: window.localStorage.getItem('photo') || ''
      photo: window.localStorage.getItem('photo')
    }
  },
  mutations: {
    setToken (state, tokenStr) {
      state.token = tokenStr
      // window.localStorage.setItem('token', tokenStr)
      Storage.set('token', tokenStr)
    },
    setRefreshToken (state, restokenStr) {
      state.refreshToken = restokenStr
      // window.localStorage.setItem('refresh_token', restokenStr)
      Storage.set('refresh_token', restokenStr)
    },
    // 用户信息
    setUserInfo (state, userObj) {
      state.userInfo = userObj
    },
    setUserName (state, val) {
      state.userInfo.name = val
    },
    // 更改用户头像
    setUserPhoto (state, val) {
      state.userInfo.photo = val
      // 头像本地存储 防止刷新后头像不能正常显示
      // window.localStorage.setItem('photo', val)
      Storage.set('photo', val)
    }
  },
  actions: {
    async asyLoginAction (store, fromLogin) {
      // 1 发送登录请求
      const resp = await loginAPI(fromLogin)
      // 对解构的属性重命名
      const { token, refresh_token: refreshToken } = resp.data
      // 2 提交到mutations 同步token 和 refreshToken
      store.commit('setToken', token)
      store.commit('setRefreshToken', refreshToken)
    }
  },
  modules: {
  }
})

export default store
